<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import BrowserTab from '../components/browser/BrowserTab.vue';
import BrowserWebView from '../components/browser/BrowserWebView.vue';
import AddressBar from '../components/browser/AddressBar.vue';
import BookmarkBar from '../components/browser/BookmarkBar.vue';

// 导入electron-env.d.ts中的ElectronAPI类型
declare global {
  interface Window {
    elec: ElectronAPI;
  }
}

const { t } = useI18n();

// 标签页数据结构
interface TabItem {
  id: string;
  title: string;
  url: string;
  icon?: string;
  loading: boolean;
  active: boolean;
  isolationGroup?: number; // 隔离分组ID
  privateMode: boolean; // 无痕模式
  canGoBack: boolean;
  canGoForward: boolean;
  isSecure: boolean;
  isHibernated?: boolean; // 标签是否处于休眠状态
  hasError?: boolean; // 页面是否加载出错
  errorDescription?: string; // 错误描述
}

// 标签页状态
const tabs = reactive<TabItem[]>([]);
const activeTabId = ref<string>('');
const showContextMenu = ref(false);
const contextMenuPosition = reactive({ x: 0, y: 0 });
const contextMenuTabId = ref<string>('');
const defaultUrl = 'https://www.bing.com';
const newTabPage = 'about:newtab';
const bookmarkBarRef = ref<any>(null);
const windowId = ref<number | null>(null);

// 当前激活的标签页
const activeTab = computed(() => {
  return tabs.find(tab => tab.id === activeTabId.value);
});

// 当前打开的右键菜单标签
const contextMenuTab = computed(() => {
  return tabs.find(tab => tab.id === contextMenuTabId.value);
});

// 初始化
async function initialize() {
  try {
    // 获取当前窗口ID
    windowId.value = await window.elec.window.getCurrentWindowId();
    
    // 创建初始标签页
    if (windowId.value !== null) {
      createNewTab(defaultUrl);
      
      // 定期清理内存
      setupMemoryManagement();
    } else {
      ElMessage.error('无法获取窗口ID');
    }
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('初始化失败');
  }
}

// 设置内存管理
function setupMemoryManagement() {
  // 每5分钟检查一次不活跃标签，如果有超过10个标签则考虑释放内存
  const interval = setInterval(() => {
    if (windowId.value === null) {
      clearInterval(interval);
      return;
    }
    
    // 如果标签数超过限制，尝试释放不活跃标签的内存
    if (tabs.length > 10) {
      const activeTabIndex = tabs.findIndex(tab => tab.id === activeTabId.value);
      
      // 找出距离当前标签最远的非活跃标签
      const tabsToRelease = tabs
        .map((tab, index) => ({
          tab,
          index,
          distance: Math.abs(index - activeTabIndex)
        }))
        .filter(item => item.distance > 3) // 只考虑距离当前标签较远的标签
        .sort((a, b) => b.distance - a.distance); // 按距离从大到小排序
      
      // 释放最远的标签内存
      if (tabsToRelease.length > 0) {
        const furthestTab = tabsToRelease[0];
        window.elec.tab.hibernateTab(windowId.value, furthestTab.index)
          .catch(error => console.error('休眠标签失败:', error));
      }
    }
  }, 5 * 60 * 1000); // 5分钟
  
  // 在组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(interval);
  });
}

// 创建新标签
const createNewTab = async (url: string = newTabPage, isolationGroup?: number, privateMode: boolean = false) => {
  if (windowId.value === null) return;
  
  try {
    // 调用主进程API创建标签页
    const tabId = await window.elec.tab.createTab(windowId.value, url);
    
    // 创建本地标签数据用于UI显示
    const newTab: TabItem = {
      id: String(tabId),
      title: t('browser.newTab'),
      url,
      loading: true,
      active: false,
      isolationGroup,
      privateMode,
      canGoBack: false,
      canGoForward: false,
      isSecure: url.startsWith('https://')
    };
    
    // 设置所有标签为非激活
    tabs.forEach(tab => tab.active = false);
    
    // 添加新标签并激活
    tabs.push(newTab);
    newTab.active = true;
    activeTabId.value = newTab.id;
    
    return newTab.id;
  } catch (error) {
    console.error('创建标签页失败:', error);
    ElMessage.error('创建标签页失败');
    return undefined;
  }
};

// 关闭标签
const closeTab = async (index: number) => {
  if (index < 0 || index >= tabs.length || windowId.value === null) return;
  
  const tabId = tabs[index].id;
  
  try {
    // 调用主进程API关闭标签页
    await window.elec.tab.closeTab(windowId.value, index);
    
    // 如果是最后一个标签，创建一个新标签
    if (tabs.length === 1) {
      tabs.splice(index, 1);
      createNewTab();
      return;
    }
    
    const isActive = tabId === activeTabId.value;
    tabs.splice(index, 1);
    
    // 如果关闭的是当前激活的标签，激活左侧或右侧的标签
    if (isActive) {
      const newActiveIndex = Math.min(index, tabs.length - 1);
      await activateTab(newActiveIndex);
    }
  } catch (error) {
    console.error('关闭标签页失败:', error);
    ElMessage.error('关闭标签页失败');
  }
};

// 更新标签信息
const updateTab = (tabId: string, data: Partial<TabItem>) => {
  const tab = tabs.find(tab => tab.id === tabId);
  if (!tab) return;
  
  Object.assign(tab, data);
};

// 激活标签
const activateTab = async (index: number) => {
  if (index >= 0 && index < tabs.length && windowId.value !== null) {
    try {
      // 调用主进程API切换标签页
      await window.elec.tab.switchTab(windowId.value, index);
      
      // 更新UI状态
      tabs.forEach(tab => tab.active = false);
      tabs[index].active = true;
      activeTabId.value = tabs[index].id;
    } catch (error) {
      console.error('激活标签页失败:', error);
      ElMessage.error('激活标签页失败');
    }
  }
};

// 切换到下一个标签
const nextTab = () => {
  if (tabs.length <= 1) return;
  
  const currentIndex = tabs.findIndex(tab => tab.id === activeTabId.value);
  const nextIndex = (currentIndex + 1) % tabs.length;
  
  activateTab(nextIndex);
};

// 切换到上一个标签
const previousTab = () => {
  if (tabs.length <= 1) return;
  
  const currentIndex = tabs.findIndex(tab => tab.id === activeTabId.value);
  const prevIndex = (currentIndex - 1 + tabs.length) % tabs.length;
  
  activateTab(prevIndex);
};

// 打开右键菜单
const openContextMenu = (event: MouseEvent, index: number) => {
  event.preventDefault();
  contextMenuPosition.x = event.clientX;
  contextMenuPosition.y = event.clientY;
  contextMenuTabId.value = tabs[index].id;
  showContextMenu.value = true;
  
  document.addEventListener('click', closeContextMenu, { once: true });
};

// 关闭右键菜单
const closeContextMenu = () => {
  showContextMenu.value = false;
};

// 在新标签中打开
const openInNewTab = (url?: string) => {
  if (!url) return;
  createNewTab(url, contextMenuTab.value?.isolationGroup);
  closeContextMenu();
};

// 在新隔离标签中打开
const openInNewIsolatedTab = (url?: string) => {
  if (!url) return;
  // 获取当前最大的隔离组ID并加1
  const maxGroupId = Math.max(0, ...tabs.map(tab => tab.isolationGroup || 0));
  const newGroupId = maxGroupId + 1;
  createNewTab(url, newGroupId);
  closeContextMenu();
};

// 在无痕模式下打开
const openInPrivateMode = (url?: string) => {
  if (!url) return;
  createNewTab(url, undefined, true);
  closeContextMenu();
};

// 在新窗口中打开
const openInNewWindow = (url?: string) => {
  if (!url) return;
  window.elec.window.createWindow(url);
  closeContextMenu();
};

// 刷新当前标签
const refreshCurrentTab = async () => {
  if (!activeTab.value || windowId.value === null) return;
  
  const index = tabs.findIndex(tab => tab.id === activeTabId.value);
  if (index === -1) return;
  
  try {
    // 调用主进程API刷新标签页
    await window.elec.tab.refreshTab(windowId.value, index);
    
    // 更新UI状态
    updateTab(activeTabId.value, { loading: true });
  } catch (error) {
    console.error('刷新标签页失败:', error);
    ElMessage.error('刷新失败');
  }
};

// 后退
const goBack = async () => {
  if (!activeTab.value || !activeTab.value.canGoBack || windowId.value === null) return;
  
  const index = tabs.findIndex(tab => tab.id === activeTabId.value);
  if (index === -1) return;
  
  try {
    // 调用主进程API执行后退
    await window.elec.tab.goBack(windowId.value, index);
  } catch (error) {
    console.error('后退失败:', error);
    ElMessage.error('后退失败');
  }
};

// 前进
const goForward = async () => {
  if (!activeTab.value || !activeTab.value.canGoForward || windowId.value === null) return;
  
  const index = tabs.findIndex(tab => tab.id === activeTabId.value);
  if (index === -1) return;
  
  try {
    // 调用主进程API执行前进
    await window.elec.tab.goForward(windowId.value, index);
  } catch (error) {
    console.error('前进失败:', error);
    ElMessage.error('前进失败');
  }
};

// 打开历史记录页面
const openHistory = () => {
  createNewTab('chrome://history');
};

// 打开下载页面
const openDownloads = () => {
  createNewTab('chrome://downloads');
};

// 打开扩展程序页面
const openExtensions = () => {
  createNewTab('chrome://extensions');
};

// 打开设置页面
const openSettings = () => {
  createNewTab('chrome://settings');
};

// 在当前标签中导航
const navigateTab = async (url: string) => {
  if (!activeTab.value || windowId.value === null) return;
  
  const index = tabs.findIndex(tab => tab.id === activeTabId.value);
  if (index === -1) return;
  
  try {
    // 调用主进程API导航到URL
    await window.elec.tab.navigateTo(windowId.value, index, url);
    
    // 更新UI状态
    updateTab(activeTabId.value, { 
      url, 
      loading: true,
      isSecure: url.startsWith('https://')
    });
  } catch (error) {
    console.error('导航失败:', error);
    ElMessage.error('导航失败');
  }
};

// 添加书签
const addBookmark = async () => {
  const tab = activeTab.value;
  if (!tab || tab.url === newTabPage) return;
  
  if (bookmarkBarRef.value) {
    await bookmarkBarRef.value.addBookmark(
      tab.url,
      tab.title,
      tab.icon
    );
  }
};

// 处理标签更新
const handleTabUpdate = (tabId: string, tabData: any) => {
  updateTab(tabId, {
    ...tabData,
    isSecure: tabData.url?.startsWith('https://')
  });
};

// 处理导航操作
const handleNavigateTab = (tabId: string, url: string) => {
  // 在新标签页中打开
  createNewTab(url);
};

// 处理上下文菜单
const handleContextMenu = (tabId: string, data: any) => {
  if (data.action === 'open-link-menu') {
    // 处理链接的右键菜单
    ElMessageBox.confirm('您想要如何处理此链接?', '链接选项', {
      confirmButtonText: '在新标签页中打开',
      cancelButtonText: '取消',
      distinguishCancelAndClose: true,
      type: 'info'
    }).then(() => {
      createNewTab(data.url);
    }).catch(() => {
      // 用户取消操作
    });
  }
};

// 处理地址栏导航
const handleAddressBarNavigate = (url: string) => {
  navigateTab(url);
};

// 组件挂载时
onMounted(() => {
  initialize();
  
  // 添加快捷键事件监听
  document.addEventListener('keydown', handleKeyDown);
  
  // 监听新窗口请求
  const removeNewWindowListener = window.elec.tab.onNewWindowRequest((data: any) => {
    // 根据打开方式处理URL
    switch (data.disposition) {
      case 'new-window':
        openInNewWindow(data.url);
        break;
      case 'background-tab':
        createNewTab(data.url);
        break;
      case 'foreground-tab':
        createNewTab(data.url).then(() => {
          // 确保标签创建后被激活
          const index = tabs.length - 1;
          if (index >= 0) {
            activateTab(index);
          }
        });
        break;
      default:
        // 默认在当前标签打开
        navigateTab(data.url);
        break;
    }
  });
  
  // 监听标签页关闭事件
  const removeTabClosedListener = window.elec.tab.onTabClosed((closedTabId: number) => {
    // 查找对应的标签并从UI移除，保持与主进程同步
    const index = tabs.findIndex(tab => tab.id === String(closedTabId));
    if (index !== -1) {
      const wasActive = tabs[index].active;
      tabs.splice(index, 1);
      
      // 如果关闭的是活动标签，激活新标签
      if (wasActive && tabs.length > 0) {
        const newActiveIndex = Math.min(index, tabs.length - 1);
        tabs[newActiveIndex].active = true;
        activeTabId.value = tabs[newActiveIndex].id;
      }
      
      // 如果没有标签了，创建一个新标签
      if (tabs.length === 0) {
        createNewTab();
      }
    }
  });
  
  // 组件卸载时移除事件监听
  onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyDown);
    removeNewWindowListener();
    removeTabClosedListener();
  });
});

// 处理快捷键
const handleKeyDown = (event: KeyboardEvent) => {
  // Ctrl+T: 新建标签页
  if (event.ctrlKey && event.key === 't') {
    event.preventDefault();
    createNewTab();
  }
  
  // Ctrl+W: 关闭当前标签页
  if (event.ctrlKey && event.key === 'w') {
    event.preventDefault();
    const index = tabs.findIndex(tab => tab.id === activeTabId.value);
    if (index !== -1) {
      closeTab(index);
    }
  }
  
  // Ctrl+Tab: 切换到下一个标签
  if (event.ctrlKey && event.key === 'Tab' && !event.shiftKey) {
    event.preventDefault();
    nextTab();
  }
  
  // Ctrl+Shift+Tab: 切换到上一个标签
  if (event.ctrlKey && event.shiftKey && event.key === 'Tab') {
    event.preventDefault();
    previousTab();
  }
  
  // Ctrl+R: 刷新页面
  if (event.ctrlKey && event.key === 'r') {
    event.preventDefault();
    refreshCurrentTab();
  }
  
  // Ctrl+D: 添加书签
  if (event.ctrlKey && event.key === 'd') {
    event.preventDefault();
    addBookmark();
  }
};
</script>

<template>
  <div class="browser-container">
    <!-- 顶部拖拽区域 -->
    <div class="drag-region" data-tauri-drag-region></div>
    
    <!-- 顶部标签栏 -->
    <div class="browser-tabs-container">
      <div class="browser-tabs" data-tauri-drag-region>
        <BrowserTab
          v-for="(tab, index) in tabs"
          :key="tab.id"
          :tab="tab"
          :index="index"
          @click="activateTab(index)"
          @close="closeTab(index)"
          @contextmenu="openContextMenu($event, index)"
        />
        <div class="new-tab-button" @click="createNewTab()">
          <el-icon><Plus /></el-icon>
        </div>
      </div>
    </div>
    
    <!-- 地址栏 -->
    <div class="browser-address-container">
      <AddressBar
        :url="activeTab?.url || ''"
        :title="activeTab?.title"
        :is-loading="activeTab?.loading || false"
        :can-go-back="activeTab?.canGoBack || false"
        :can-go-forward="activeTab?.canGoForward || false"
        :is-secure="activeTab?.isSecure || false"
        @navigate="handleAddressBarNavigate"
        @refresh="refreshCurrentTab"
        @go-back="goBack"
        @go-forward="goForward"
      />
    </div>
    
    <!-- 书签栏 -->
    <BookmarkBar
      ref="bookmarkBarRef"
      @navigate="url => createNewTab(url)"
    />
    
    <!-- 内容区域 -->
    <div class="browser-content">
      <BrowserWebView
        v-for="(tab, index) in tabs"
        :key="tab.id"
        :tab-id="tab.id"
        :url="tab.url"
        :active="tab.id === activeTabId"
        :isolation-group="tab.isolationGroup"
        :private-mode="tab.privateMode"
        :window-id="windowId || 0"
        :index="index"
        @update:tab="tabData => handleTabUpdate(tab.id, tabData)"
        @navigate="url => handleNavigateTab(tab.id, url)"
        @contextmenu="data => handleContextMenu(tab.id, data)"
      />
    </div>
    
    <!-- 右键菜单 -->
    <div v-if="showContextMenu" class="context-menu" :style="{
      left: `${contextMenuPosition.x}px`,
      top: `${contextMenuPosition.y}px`
    }">
      <!-- 在新标签中打开 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          if (contextMenuTab && contextMenuTab.url) openInNewTab(contextMenuTab.url);
          closeContextMenu();
        }"
      >
        {{ t('browser.contextMenu.openInNewTab') }}
      </div>
      
      <!-- 在新窗口中打开 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          if (contextMenuTab && contextMenuTab.url) openInNewWindow(contextMenuTab.url);
          closeContextMenu();
        }"
      >
        {{ t('browser.contextMenu.openInNewWindow') }}
      </div>
      
      <!-- 在新隔离标签中打开 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          if (contextMenuTab && contextMenuTab.url) openInNewIsolatedTab(contextMenuTab.url);
          closeContextMenu();
        }"
      >
        {{ t('browser.contextMenu.openInPrivateMode') }}
      </div>
      
      <!-- 在无痕模式中打开 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          if (contextMenuTab && contextMenuTab.url) openInPrivateMode(contextMenuTab.url);
          closeContextMenu();
        }"
      >
        {{ t('browser.contextMenu.openInPrivateMode') }}
      </div>
      
      <!-- 关闭标签页 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          if (contextMenuTabId) {
            const i = tabs.findIndex(tab => tab.id === contextMenuTabId);
            if (i !== -1) closeTab(i);
          }
          closeContextMenu();
        }"
      >
        {{ t('browser.contextMenu.closeTab') }}
      </div>
      
      <!-- 添加书签 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          addBookmark();
          closeContextMenu();
        }"
      >
        {{ t('browser.bookmarks.addBookmark') }}
      </div>
      
      <div class="context-menu-divider"></div>
      
      <!-- 历史记录 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          openHistory();
          closeContextMenu();
        }"
      >
        {{ t('browser.history.title') }}
      </div>
      
      <!-- 下载 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          openDownloads();
          closeContextMenu();
        }"
      >
        {{ t('browser.downloads.title') }}
      </div>
      
      <!-- 设置 -->
      <div 
        class="context-menu-item" 
        @click="() => {
          openSettings();
          closeContextMenu();
        }"
      >
        {{ t('browser.settings.title') }}
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.browser-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  background-color: var(--el-bg-color);
}

.drag-region {
  height: 3px;
  width: 100%;
  -webkit-app-region: drag;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
}

.browser-tabs-container {
  display: flex;
  height: 40px;
  background-color: #f2f2f2;
  border-bottom: 1px solid #dadce0;
  user-select: none;
  padding-right: 140px; /* 为原生窗口按钮预留空间 */
  
  :global(html.dark) & {
    background-color: #202124;
    border-bottom-color: #3c4043;
  }
}

.browser-tabs {
  display: flex;
  flex: 1;
  overflow-x: auto;
  scrollbar-width: none;
  margin-left: 8px;
  
  &::-webkit-scrollbar {
    display: none;
  }
}

.new-tab-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  margin-top: 4px;
  border-radius: 50%;
  cursor: pointer;
  color: #5f6368;
  background-color: transparent;
  
  &:hover {
    background-color: rgba(0, 0, 0, 0.06);
    color: #202124;
  }
  
  :global(html.dark) & {
    color: #9aa0a6;
    
    &:hover {
      background-color: rgba(255, 255, 255, 0.1);
      color: #e8eaed;
    }
  }
}

.browser-address-container {
  padding: 4px 8px;
  background-color: #f2f2f2;
  
  :global(html.dark) & {
    background-color: #202124;
  }
}

.browser-content {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.context-menu {
  position: fixed;
  background-color: white;
  border: 1px solid #dadce0;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  padding: 8px 0;
  z-index: 3000;
  min-width: 200px;
  
  :global(html.dark) & {
    background-color: #292a2d;
    border-color: #3c4043;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  }
}

.context-menu-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #202124;
  display: flex;
  align-items: center;
  
  :global(html.dark) & {
    color: #e8eaed;
  }
  
  &:hover {
    background-color: #f2f2f2;
    
    :global(html.dark) & {
      background-color: #3c4043;
    }
  }
}

.context-menu-divider {
  height: 1px;
  background-color: #dadce0;
  margin: 4px 0;
  
  :global(html.dark) & {
    background-color: #3c4043;
  }
}
</style>
